package com.hw.protocol.tool.view;

import com.hw.protocol.tool.util.CrcUtil;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

/**
 * @author : lihy
 * @date : 2023/9/21 17:20
 * description: 龙口金卡协议工具类
 */
public class TxUtil {

    /**
     * 取字节数组之和的低位
     *
     * @param data 需要计算的字节数组
     */
    public static byte getVerify(byte[] data) {
        int verify = 0;
        for (Byte b : data) {
            verify += b & 0xFF;
        }
        return (byte) (verify & 0xFF);
    }

    /**
     * 计算校验和
     * @param data 接收数据
     */
    public static boolean checkVerify(byte[] data) {
        byte[] checkBytes = Arrays.copyOfRange(data, 0, data.length - 3);
        byte[] verifyBytes = Arrays.copyOfRange(data, data.length - 3, data.length - 1);
        int verify = 0;
        for (byte checkByte : checkBytes) {
            verify += checkByte & 0xFF;
        }
        int calculate = ByteBuffer.wrap(verifyBytes).order(ByteOrder.LITTLE_ENDIAN).getShort();
        return verify == calculate;
    }

    /**
     * 计算浮点数据
     *
     * @param data 浮点数据字节数组
     */
    public static float calculateFloat(byte[] data) {
        int[] ten = new int[4];
        for (int i = 0; i < data.length; i++) {
            ten[i] = data[i] & 0xFF;
        }
        if (ten[0] >= 128) {
            ten[0] = ten[0] - 256;
        }
        if (ten[1] >= 128) {
            ten[1] = 128 - ten[1];
            ten[2] = -ten[2];
            ten[3] = -ten[3];
        }
        long a = (ten[1] * 256 + ten[2]) * 256 + ten[3];
        long b = (int) Math.pow(2, ten[0]);
        long ab = a * b;
        return ab / 8388608f;
    }

    /**
     * 计算百万位数据
     *
     * @param data 百万位数据字节数组
     */
    public static long calculateMillion(byte[] data) {
        return Long.parseLong(CrcUtil.bytesToHex(data, false)) * (long) Math.pow(10, 6);
    }

    /**
     * 获取时间
     *
     * @param data 时间字节数组
     */
    public static String getTime(byte[] data) {
        return String.format("%02d%02d-%02d-%02d %02d:%02d:%02d",
                getInt(data[0]),
                getInt(data[1]),
                getInt(data[2]),
                getInt(data[3]),
                getInt(data[4]),
                getInt(data[5]),
                getInt(data[6]));
    }

    /**
     * BCD码解析
     *
     * @param b 需要解析的字节
     */
    private static int getInt(byte b) {
        return Integer.parseInt(Integer.toHexString(b & 0xff));
    }
}
